package com.spring.nio.core.reactor.selector;

import com.spring.nio.common.BasicConstant;
import com.spring.nio.core.channel.context.SocketChannelContext;
import com.spring.nio.core.event.model.EventModel;
import com.spring.nio.core.event.model.EventModelEnum;
import com.spring.nio.util.NioUtil;
import lombok.extern.slf4j.Slf4j;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @Auther: YSFY
 * @Date: 2020-11-21 11:30
 * @Pacage_name: com.spring.nio.core.reactor.selector
 * @Project_Name: net-server
 * @Description: 公共Selector处理类
 */
@Slf4j
@SuppressWarnings("all")
public class AbstractSelector {

    /**
     * 装饰EventModel类
     * @param eventModel 当前通道产生的事件模型
     * @param selectionKey 当前通道产生的可选键 selectionKey
     */
    public void decorateEventModel(EventModel eventModel, SelectionKey selectionKey) {
        eventModel.setSelectionKey(selectionKey);

        // 客户端通道(包括上传或下载客户端通道)
        if(selectionKey.channel() instanceof SocketChannel) {
            SocketChannelContext socketChannelContext = (SocketChannelContext) selectionKey.attachment();
            eventModel.setRemoteAddress(socketChannelContext.getRemoteAddress()); // 远程地址
            if(socketChannelContext.getLocalAddress().contains(NioUtil.getValue(BasicConstant.NIO_FILE_UPLOAD_PORT))) {
                eventModel.setEventModelEnum(EventModelEnum.FILE_UPLOAD_EVENT_ACCEPTOR);
            }
            if(socketChannelContext.getLocalAddress().contains(NioUtil.getValue(BasicConstant.NIO_FILE_DOWNLOAD_PORT))) {
                eventModel.setEventModelEnum(EventModelEnum.FILE_DOWNLOAD_EVENT_ACCEPTOR);
            }
        }

        // 如果触发事件的通道类型为: 服务端通道
        if(selectionKey.channel() instanceof ServerSocketChannel) {
            eventModel.setLocalAddress(NioUtil.getServerLocalAddress(((ServerSocketChannel) selectionKey.channel()))); // 本地地址
            // 根据本地对外暴露端口号判断是文件上传socket还是下载socket，以此来设置eventModel当前事件类型
            if(eventModel.getLocalAddress().contains(NioUtil.getValue(BasicConstant.NIO_FILE_UPLOAD_PORT))) {
                eventModel.setEventModelEnum(EventModelEnum.FILE_UPLOAD_EVENT_ACCEPTOR);
            }

            if(eventModel.getLocalAddress().contains(NioUtil.getValue(BasicConstant.NIO_FILE_DOWNLOAD_PORT))) {
                eventModel.setEventModelEnum(EventModelEnum.FILE_DOWNLOAD_EVENT_ACCEPTOR);
            }
        }

    }
}
